import { useCallback, useEffect, useRef } from 'react'
import Taro from '@tarojs/taro'
import { get } from '../axios/aiaxios/request'

// 预加载配置
const PRELOAD_CONFIG = {
  // 预加载延迟时间（毫秒）
  DELAY: 1000,
  // 最大并发预加载数
  MAX_CONCURRENT: 3,
  // 预加载缓存时间（毫秒）
  CACHE_TIME: 5 * 60 * 1000
}

// 预加载队列
const preloadQueue = []
const preloadCache = new Map()
let isProcessing = false

// 预加载管理器
class PreloadManager {
  constructor() {
    this.queue = []
    this.cache = new Map()
    this.processing = false
  }

  // 添加到队列
  addToQueue(task) {
    this.queue.push(task)
    this.processQueue()
  }

  // 处理队列
  async processQueue() {
    if (this.processing || this.queue.length === 0) return

    this.processing = true

    while (this.queue.length > 0) {
      const tasks = this.queue.splice(0, PRELOAD_CONFIG.MAX_CONCURRENT)
      
      await Promise.allSettled(
        tasks.map(task => this.executeTask(task))
      )

      // 延迟处理下一批
      if (this.queue.length > 0) {
        await new Promise(resolve => setTimeout(resolve, PRELOAD_CONFIG.DELAY))
      }
    }

    this.processing = false
  }

  // 执行预加载任务
  async executeTask(task) {
    const { key, fetcher, onSuccess, onError } = task

    try {
      // 检查缓存
      const cached = this.cache.get(key)
      if (cached && Date.now() - cached.timestamp < PRELOAD_CONFIG.CACHE_TIME) {
        onSuccess?.(cached.data)
        return
      }

      // 执行预加载
      const data = await fetcher()
      
      // 缓存结果
      this.cache.set(key, {
        data,
        timestamp: Date.now()
      })

      onSuccess?.(data)
    } catch (error) {
      console.error('预加载失败:', error)
      onError?.(error)
    }
  }

  // 获取缓存数据
  getCachedData(key) {
    const cached = this.cache.get(key)
    if (cached && Date.now() - cached.timestamp < PRELOAD_CONFIG.CACHE_TIME) {
      return cached.data
    }
    return null
  }

  // 清除缓存
  clearCache(key) {
    if (key) {
      this.cache.delete(key)
    } else {
      this.cache.clear()
    }
  }
}

// 全局预加载管理器
const preloadManager = new PreloadManager()

// 数据预加载Hook
export const usePreload = () => {
  const preloadRef = useRef(new Set())

  // 预加载商品数据
  const preloadProducts = useCallback((category = '热门') => {
    const key = `products_${category}`
    
    if (preloadRef.current.has(key)) return

    preloadRef.current.add(key)
    
    preloadManager.addToQueue({
      key,
      fetcher: async () => {
        const response = await get('/cosmetic/products', { category, limit: 20 })
        
        if (response.success) {
          return response.data || []
        }
        throw new Error('预加载商品数据失败')
      },
      onSuccess: (data) => {
        if (process.env.NODE_ENV === 'development') {
          console.log(`预加载商品数据成功: ${category}`, data.length)
        }
      },
      onError: (error) => {
        console.error(`预加载商品数据失败: ${category}`, error)
      }
    })
  }, [])

  // 预加载医院数据
  const preloadHospitals = useCallback((category = '热门') => {
    const key = `hospitals_${category}`
    
    if (preloadRef.current.has(key)) return

    preloadRef.current.add(key)
    
    preloadManager.addToQueue({
      key,
      fetcher: async () => {
        const response = await get('/cosmetic/hospitals', { category, limit: 20 })
        
        if (response.success) {
          return response.data || []
        }
        throw new Error('预加载医院数据失败')
      },
      onSuccess: (data) => {
        if (process.env.NODE_ENV === 'development') {
          console.log(`预加载医院数据成功: ${category}`, data.length)
        }
      },
      onError: (error) => {
        console.error(`预加载医院数据失败: ${category}`, error)
      }
    })
  }, [])

  // 预加载医生数据
  const preloadDoctors = useCallback((category = '热门') => {
    const key = `doctors_${category}`
    
    if (preloadRef.current.has(key)) return

    preloadRef.current.add(key)
    
    preloadManager.addToQueue({
      key,
      fetcher: async () => {
        const response = await get('/cosmetic/doctors', { category, limit: 20 })
        
        if (response.success) {
          return response.data || []
        }
        throw new Error('预加载医生数据失败')
      },
      onSuccess: (data) => {
        if (process.env.NODE_ENV === 'development') {
          console.log(`预加载医生数据成功: ${category}`, data.length)
        }
      },
      onError: (error) => {
        console.error(`预加载医生数据失败: ${category}`, error)
      }
    })
  }, [])

  // 预加载详情页数据
  const preloadDetail = useCallback((type, id) => {
    const key = `${type}_detail_${id}`
    
    if (preloadRef.current.has(key)) return

    preloadRef.current.add(key)
    
    preloadManager.addToQueue({
      key,
      fetcher: async () => {
        const response = await get(`/cosmetic/${type}/${id}`)
        
        if (response.success) {
          return response.data
        }
        throw new Error(`预加载${type}详情失败`)
      },
      onSuccess: (data) => {
        if (process.env.NODE_ENV === 'development') {
          console.log(`预加载${type}详情成功:`, data.name || data.title)
        }
      },
      onError: (error) => {
        console.error(`预加载${type}详情失败:`, error)
      }
    })
  }, [])

  // 预加载图片 - 简化版本，避免使用new Image()
  const preloadImage = useCallback((src) => {
    if (!src) return

    const key = `image_${src}`
    
    if (preloadRef.current.has(key)) return

    preloadRef.current.add(key)
    
    // 简化处理：直接记录预加载状态，不实际预加载
    if (process.env.NODE_ENV === 'development') {
      console.log('图片预加载记录:', src)
    }
  }, [])

  // 批量预加载
  const preloadBatch = useCallback((tasks) => {
    tasks.forEach(task => {
      const { type, ...params } = task
      
      switch (type) {
        case 'products':
          preloadProducts(params.category)
          break
        case 'hospitals':
          preloadHospitals(params.category)
          break
        case 'doctors':
          preloadDoctors(params.category)
          break
        case 'detail':
          preloadDetail(params.detailType, params.id)
          break
        case 'image':
          preloadImage(params.src)
          break
      }
    })
  }, [preloadProducts, preloadHospitals, preloadDoctors, preloadDetail, preloadImage])

  // 获取缓存数据
  const getCachedData = useCallback((key) => {
    return preloadManager.getCachedData(key)
  }, [])

  // 清除缓存
  const clearCache = useCallback((key) => {
    preloadManager.clearCache(key)
  }, [])

  return {
    preloadProducts,
    preloadHospitals,
    preloadDoctors,
    preloadDetail,
    preloadImage,
    preloadBatch,
    getCachedData,
    clearCache
  }
}

// 预加载策略Hook
export const usePreloadStrategy = () => {
  const { preloadProducts, preloadHospitals, preloadDoctors, preloadDetail } = usePreload()

  // 预加载当前标签页数据
  const preloadCurrentTab = useCallback((activeTab) => {
    switch (activeTab) {
      case '钜惠商品':
        preloadProducts('热门')
        preloadProducts('新品')
        preloadProducts('特价')
        break
      case '甄选机构':
        preloadHospitals('热门')
        preloadHospitals('三甲')
        preloadHospitals('专科')
        break
      case '口碑医生':
        preloadDoctors('热门')
        preloadDoctors('专家')
        preloadDoctors('主任')
        break
    }
  }, [preloadProducts, preloadHospitals, preloadDoctors])

  // 预加载相邻标签页数据
  const preloadAdjacentTabs = useCallback((activeTab) => {
    const tabs = ['钜惠商品', '甄选机构', '口碑医生']
    const currentIndex = tabs.indexOf(activeTab)
    
    // 预加载相邻标签页
    const adjacentIndexes = [
      (currentIndex - 1 + tabs.length) % tabs.length,
      (currentIndex + 1) % tabs.length
    ]
    
    adjacentIndexes.forEach(index => {
      const tab = tabs[index]
      preloadCurrentTab(tab)
    })
  }, [preloadCurrentTab])

  // 预加载详情页相关数据
  const preloadDetailRelated = useCallback((type, id) => {
    // 预加载详情页数据
    preloadDetail(type, id)
    
    // 预加载相关数据
    if (type === 'products') {
      preloadProducts('相关')
    } else if (type === 'hospitals') {
      preloadHospitals('相关')
    }
  }, [preloadDetail, preloadProducts, preloadHospitals])

  return {
    preloadCurrentTab,
    preloadAdjacentTabs,
    preloadDetailRelated
  }
}

export default usePreload
